var oper = getQueryString('oper')
var menuId = getQueryString('id')
$(function () {

  $(document).on('focus', "input[name='icon']", function () {
    $(".icon-drop").show();
  });
  $(document).on('click', "#editForm", function (event) {
    var obj = event.srcElement || event.target;
    if (!$(obj).is("input[name='icon']")) {
      $(".icon-drop").hide();
    }
  });
  $(document).on("click", ".icon-drop .ico-list i",
    function () {
      $('#icon').val($(this).attr('class'));
    });

  $(document).on('ifChecked', 'input',
    function (event) {
      var menuType = $(event.target).val();
      menuVisible(menuType);
    });


  if (oper === 'edit') {
    menuDetail(menuId)
  } else {
    var result = {
      oper: oper,
      type: '0'
    }
    renderTpl('menuFormTpl', result, 'menuFormBox')
    tplInit()
    validateForm()
    menuVisible("0");
    $('#iconList').load('/pages/sysadm/menu/icon')
  }
});

function menuVisible(menuType) {
  if (menuType == "0") {
    $("#path").parents(".form-group").show();
    $("#permission").parents(".form-group").hide();
    $("#icon").parents(".form-group").show();
  } else if (menuType == "1") {
    $("#path").parents(".form-group").hide();
    $("#permission").parents(".form-group").show();
    $("#icon").parents(".form-group").hide();
  }
}

function menuDetail(id) {
  $.operate.get(api + '/admin/menu/' + id, function (res) {
    // applyDrawing('#editForm',res.data)
    res.data.oper = oper
    res.data.parentName = res.data.parentName || '无'
    renderTpl('menuFormTpl', res.data, 'menuFormBox')
    tplInit()
    menuVisible(res.data.type)
    validateForm()
    $('#iconList').load('/pages/sysadm/menu/icon')
  }, false)
}

function selectMenuTree() {
  if ($("#oper").val() == 'add') {
    var menuId = $("#treeId").val();
    var url = "/pages/sysadm/menu/tree?menuId"+menuId;
    var options = {
      title: '菜单选择',
      width: "380",
      url: url,
      callBack: doSubmit
    };
    $.modal.openOptions(options);
  }

}

function doSubmit(index, layero) {
  var body = layer.getChildFrame('body', index);
  $("#treeId").val(body.find('#treeId').val());
  $("#treeName").val(body.find('#treeName').val());
  layer.close(index);
}

function validateForm() {
  $("#editForm").validate({
    onkeyup: false,
    rules: {
      type: {
        required: true
      },
      name: {
        required: true
      },
      sort: {
        digits: true
      },
    },
    focusCleanup: true
  });
}

function submitHandler() {
  if ($.validate.form()) {
    $.common.ajaxCommitForm($('#editForm'), false);
    return false;
  }
}